/**
 *  JSimProd - Java simulation code for production processes
 *  Copyleft Jorge Mira Yagüe <jorge.mira.yague@gmail.com>
 *  Universidad de Alicante 2009
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * frmTask.java
 *
 * Created on 16-feb-2009, 14:00:29
 */
package gui.forms;

import gui.tools.Receiver;
import gui.tools.models.LMString;
import java.awt.Component;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import lib.model.FactoryModel;
import lib.model.ItemCategory;
import lib.model.Station;
import lib.model.distribution.DistributionType;
import lib.model.Task;
import lib.model.distribution.Distribution;
import lib.model.distribution.ExponentialDistribution;
import lib.model.distribution.NormalDistribution;
import lib.model.distribution.StaticDistribution;
import lib.model.distribution.UniformDistribution;

/**
 *
 * @author jorge
 */
public class FrmTask extends javax.swing.JDialog {

    private Task task = null;
    private FactoryModel factory;
    private ItemCategory ic;
    private Receiver parent;

    public FrmTask(Task task, FactoryModel factory, ItemCategory ic, Receiver parent) {
        initComponents();
        this.task = task;
        this.factory = factory;
        this.ic = ic;
        this.parent = parent;

        this.getRootPane().setDefaultButton(btnSave);

        String fileString = "/res/icons/logo.png";
        try {
            Image icon = ImageIO.read(getClass().getResource(fileString));
            this.setIconImage(icon);
        } catch (java.io.IOException ioe) {
            System.out.println("Error loading file: " + fileString);
        }

        for (DistributionType t : DistributionType.values()) {
            cbType.addItem(t);
        }
        //TODO mirar el tema del zorder

        if (factory != null) {
            List<String> stationList = new ArrayList<String>();
            Collection<Station> stations = factory.getStations().values();
            for (Station station : stations) {
                stationList.add(station.getName());
            }
            lstAllStations.setModel(new LMString(stationList));
        } else {
            lstAllStations.setModel(new LMString(new ArrayList<String>()));
        }
        lstConnectedStations.setModel(new LMString(new ArrayList<String>()));
        if (task != null) {
            this.setTitle("Edit task: " + task.getName());
            txtName.setText(task.getName());
            txtDescription.setText(task.getDescription());
            Distribution distribution = task.getDistribution();
            cbType.setSelectedItem(distribution.getType());
            int meanHours = (int) distribution.getMean() / 3600000;
            int meanMinutes = (int) (distribution.getMean() % 3600000) / 60000;
            txtMeanHours.setText(String.valueOf(meanHours));
            txtMeanMinutes.setText(String.valueOf(meanMinutes));
            if (distribution.getType() != DistributionType.STATIC) {
                int varianceHours = (int) distribution.getVariance() / 3600000;
                int varianceMinutes = (int) (distribution.getVariance() % 3600000) / 60000;
                txtVarianceHours.setText(String.valueOf(varianceHours));
                txtVarianceMinutes.setText(String.valueOf(varianceMinutes));
            }
            chSameShift.setState(task.getSameShift());
            List<String> taskStationList = task.getStations();
            if (taskStationList != null) {
                LMString all = (LMString) lstAllStations.getModel();
                LMString capable = new LMString(taskStationList);
                for (String station : taskStationList) {
                    all.removeString(station);
                }
                lstAllStations.setModel(all);
                lstConnectedStations.setModel(capable);
            }
        } else {
            this.setTitle("New task:");
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblDescription = new javax.swing.JLabel();
        btnCancel = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        txtDescription = new javax.swing.JTextField();
        lblAllStations = new javax.swing.JLabel();
        spAllStations = new javax.swing.JScrollPane();
        lstAllStations = new javax.swing.JList();
        btnAddConnections = new javax.swing.JButton();
        btnRemoveConnections = new javax.swing.JButton();
        lblConnectedStations = new javax.swing.JLabel();
        spConnectedStations = new javax.swing.JScrollPane();
        lstConnectedStations = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        lblType = new javax.swing.JLabel();
        cbType = new javax.swing.JComboBox();
        lblMean = new javax.swing.JLabel();
        lblVariance = new javax.swing.JLabel();
        txtMeanHours = new javax.swing.JTextField();
        txtMeanMinutes = new javax.swing.JTextField();
        chSameShift = new java.awt.Checkbox();
        lblMeanColon = new javax.swing.JLabel();
        txtVarianceHours = new javax.swing.JTextField();
        txtVarianceMinutes = new javax.swing.JTextField();
        lblVarianceColon = new javax.swing.JLabel();

        setModal(true);
        setResizable(false);

        lblDescription.setText("Description");

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        lblAllStations.setText("All stations");

        spAllStations.setViewportView(lstAllStations);

        btnAddConnections.setText(">>");
        btnAddConnections.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddConnectionsActionPerformed(evt);
            }
        });

        btnRemoveConnections.setText("<<");
        btnRemoveConnections.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveConnectionsActionPerformed(evt);
            }
        });

        lblConnectedStations.setText("Capable stations");

        spConnectedStations.setViewportView(lstConnectedStations);

        jLabel1.setText("Name");

        lblType.setText("Type");

        cbType.setMaximumRowCount(10);
        cbType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbTypeActionPerformed(evt);
            }
        });

        lblMean.setText("Mean:");

        lblVariance.setText("Variance:");

        chSameShift.setFont(new java.awt.Font("Dialog", 1, 12));
        chSameShift.setForeground(new java.awt.Color(51, 51, 51));
        chSameShift.setLabel("Do it in the same shift");

        lblMeanColon.setText(":");

        lblVarianceColon.setText(":");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblType)
                    .addComponent(chSameShift, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblAllStations)
                            .addComponent(spAllStations, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnRemoveConnections)
                            .addComponent(btnAddConnections))
                        .addGap(6, 6, 6)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCancel))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lblConnectedStations)
                                .addComponent(spConnectedStations, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblDescription)
                            .addComponent(jLabel1)
                            .addComponent(lblMean)
                            .addComponent(lblVariance))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(txtVarianceHours, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtMeanHours, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(lblMeanColon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(lblVarianceColon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtMeanMinutes)
                                    .addComponent(txtVarianceMinutes, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 169, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cbType, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(125, 125, 125)))
                                .addGap(14, 14, 14)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDescription)
                    .addComponent(txtDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblType)
                            .addComponent(cbType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblMean)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(lblVariance))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtMeanHours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblMeanColon)
                                    .addComponent(txtMeanMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtVarianceHours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblVarianceColon)
                                    .addComponent(txtVarianceMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(chSameShift, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(lblAllStations)
                                    .addComponent(lblConnectedStations))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(spConnectedStations, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                                    .addComponent(spAllStations, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(68, 68, 68))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(60, 60, 60)
                                .addComponent(btnAddConnections)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnRemoveConnections)
                                .addContainerGap())))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnCancel)
                            .addComponent(btnSave))
                        .addContainerGap())))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-365)/2, (screenSize.height-496)/2, 365, 496);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        String name = txtName.getText();
        Distribution distribution;
        if (txtMeanHours.getText().equals("")) {
            txtMeanHours.setText("0");
        }
        if (txtMeanMinutes.getText().equals("")) {
            txtMeanMinutes.setText("0");
        }
        if (txtVarianceHours.getText().equals("")) {
            txtVarianceHours.setText("0");
        }
        if (txtVarianceMinutes.getText().equals("")) {
            txtVarianceMinutes.setText("0");
        }
        double mean = 0;
        double variance = 0;
        try {
            mean = Double.parseDouble(txtMeanHours.getText()) * 3600000 +
                    Double.parseDouble(txtMeanMinutes.getText()) * 60000;
            if (DistributionType.valueOf(cbType.getSelectedItem().toString()) !=
                    DistributionType.STATIC) {
                variance = Double.parseDouble(txtVarianceHours.getText()) * 3600000 +
                        Double.parseDouble(txtVarianceMinutes.getText()) * 60000;
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane,
                    "Error:\n Mean and variance must be bigger than zero.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        switch (DistributionType.valueOf(cbType.getSelectedItem().toString())) {
            case EXPONENTIAL:
                distribution = new ExponentialDistribution(mean, variance);
                break;
            case NORMAL:
                distribution = new NormalDistribution(mean, variance);
                break;
            case STATIC:
                distribution = new StaticDistribution(mean);
                break;
            case UNIFORM:
                distribution = new UniformDistribution(mean, variance);
                break;
            default:
                distribution = null;
                break;
        }
        String description = txtDescription.getText();
        boolean sameShift = chSameShift.getState();

        task = new Task(name, distribution, description, sameShift);
        LMString lmStations = (LMString) lstConnectedStations.getModel();
        if (!lmStations.isEmpty()) {
            List<String> stations = lmStations.getStrings();
            for (String station : stations) {
                task.addStation(station);
            }
        }
        parent.reciveObject(task);
        this.setVisible(false);
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnCancelActionPerformed

    private void cbTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbTypeActionPerformed
        boolean dstat = (DistributionType) cbType.getSelectedItem() != DistributionType.STATIC;
        txtVarianceHours.setEnabled(dstat);
        txtVarianceMinutes.setEnabled(dstat);
        txtVarianceMinutes.setEnabled(dstat);
        lblVarianceColon.setEnabled(dstat);
        lblVariance.setEnabled(dstat);
}//GEN-LAST:event_cbTypeActionPerformed

    private void btnAddConnectionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddConnectionsActionPerformed
        int index = lstAllStations.getSelectedIndex();
        if (index >= 0) {
            LMString lsmAll = (LMString) lstAllStations.getModel();
            LMString lsmCon = (LMString) lstConnectedStations.getModel();
            lsmCon.addString(lsmAll.removeString(index));
            lstAllStations.setModel(lsmAll);
            lstConnectedStations.setModel(lsmCon);
        }
    }//GEN-LAST:event_btnAddConnectionsActionPerformed

    private void btnRemoveConnectionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveConnectionsActionPerformed
        int index = lstConnectedStations.getSelectedIndex();
        if (index >= 0) {
            LMString lsmAll = (LMString) lstAllStations.getModel();
            LMString lsmCon = (LMString) lstConnectedStations.getModel();
            lsmAll.addString(lsmCon.removeString(index));
            lstAllStations.setModel(lsmAll);
            lstConnectedStations.setModel(lsmCon);
        }
    }//GEN-LAST:event_btnRemoveConnectionsActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddConnections;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnRemoveConnections;
    private javax.swing.JButton btnSave;
    private javax.swing.JComboBox cbType;
    private java.awt.Checkbox chSameShift;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel lblAllStations;
    private javax.swing.JLabel lblConnectedStations;
    private javax.swing.JLabel lblDescription;
    private javax.swing.JLabel lblMean;
    private javax.swing.JLabel lblMeanColon;
    private javax.swing.JLabel lblType;
    private javax.swing.JLabel lblVariance;
    private javax.swing.JLabel lblVarianceColon;
    private javax.swing.JList lstAllStations;
    private javax.swing.JList lstConnectedStations;
    private javax.swing.JScrollPane spAllStations;
    private javax.swing.JScrollPane spConnectedStations;
    private javax.swing.JTextField txtDescription;
    private javax.swing.JTextField txtMeanHours;
    private javax.swing.JTextField txtMeanMinutes;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtVarianceHours;
    private javax.swing.JTextField txtVarianceMinutes;
    // End of variables declaration//GEN-END:variables
}
